package com.example.project.Service.Impl;

import com.example.project.Service.CodeUtils;
import com.example.project.Service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;


@Service
public class MailServiceImpl  implements MailService {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private CodeUtils codeUtils;

    @Value("${spring.mail.username}")
    private String username;

    public int sendMailCode(String to){
        SimpleMailMessage message = new SimpleMailMessage();
        String code = codeUtils.VerifyCode();
        message.setFrom(username);
        message.setTo(to);
        message.setSubject("注册验证码");
        message.setText("欢迎使用技术分享博客网站，您的邮箱验证码为：【"+code+"】，该验证码5分钟内有效，请勿将验证码泄露给他人。");
        try{
            mailSender.send(message);
            codeUtils.setCode(to,code);
            return 1;
        } catch (MailException ex){
            return 0;
        }
    }

}
